package com.example.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.common.dto.BookListDTO;
import com.example.springboot.common.exception.ServiceException;
import com.example.springboot.common.request.AddBookRequest;
import com.example.springboot.common.request.BookListRequest;

import com.example.springboot.entity.Book;
import com.example.springboot.entity.Category;
import com.example.springboot.mapper.BookMapper;
import com.example.springboot.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.springboot.common.exception.ExceptionConstant.Exists_BookName_ERROR;
import static com.example.springboot.common.exception.ExceptionConstant.Exists_Insufficient_book_stock;


@Slf4j
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    /**
     * 根据书名模糊查询
     * @param bookListRequest
     * @return
     */
    public PageInfo<BookListDTO> page(BookListRequest bookListRequest) {
        PageHelper.startPage(bookListRequest.getPageNum(), bookListRequest.getPageSize());

        // 分级类别格式化
        String category = setCategory( bookListRequest.getCategoryList());

        // 将bookListRequest的属性赋值给BookListDTO
        BookListDTO bookListDTO = new BookListDTO();
        BeanUtils.copyProperties(bookListRequest, bookListDTO);
        bookListDTO.setCategory(category);

        List<BookListDTO> books = bookMapper.listByCondition(bookListDTO);
        return new PageInfo<>(books);
    }

    /**
     * 添加图书
     * @param addBookRequest
     * @throws Exception
     */
    public void save(AddBookRequest addBookRequest) throws Exception {
        // 分级类别格式化
        String category = setCategory(addBookRequest.getCategoryList());
        addBookRequest.setCategory(category);

        // 判断图书名称是否已经存在
        if(bookMapper.findByName(addBookRequest.getName()) != null) {
            throw new ServiceException(Exists_BookName_ERROR);
        }

        addBookRequest.setUpdateTime(new Date());

        Book book = new Book();
        BeanUtils.copyProperties(addBookRequest, book);
        bookMapper.save(book);
    }

    /**
     * 更新图书信息
     * @param addBookRequest
     * @throws Exception
     */
    public void update(AddBookRequest addBookRequest) throws Exception {
        // 分级类别格式化
        String category = setCategory(addBookRequest.getCategoryList());
        addBookRequest.setCategory(category);

        // 判断书名是否已经存在
        if (bookMapper.findByNameAndId(addBookRequest) != null) {
            throw new ServiceException(Exists_BookName_ERROR);
        }
        addBookRequest.setUpdateTime(new Date());

        Book book = new Book();
        BeanUtils.copyProperties(addBookRequest, book);
        bookMapper.update(book);
    }

    /**
     * 根据id获取需要修改的图书信息
     * @param id
     * @return
     */
    public Book getById(Integer id) {
        Book book = bookMapper.getById(id);
        return book;
    }


    /**
     * 根据id删除图书分类
     * @param id
     */
    public void deleteById(Integer id) {

        bookMapper.deleteById(id);
    }

    /**
     * 递归实现级别分类树
     * @param pid
     * @param categories
     * @return
     */
    public List<Category> createTree(Integer pid, List<Category> categories) {
        List<Category> treeList = new ArrayList<>();
        for(Category category : categories) {
            if(pid == null) {
                if(category.getPid() == null) {   // 第一级分类
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(), categories));
                }
            }
            else {
                if(pid.equals(category.getPid())) {  // 建立子树集
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(), categories));
                }
            }
            if(CollUtil.isEmpty(category.getChildren())) {
                category.setChildren(null);
            }
        }
        return treeList;
    }

    /**
     * 查询所有图书信息
     * @return
     */
    public List<Book> list() {
        return bookMapper.list();
    }


    /**
     * 分级类别格式化
     * @param categoryList
     * @return
     */
    private String setCategory(List<String> categoryList) {
        StringBuilder stringBuilder = new StringBuilder();

        if(CollUtil.isNotEmpty(categoryList)) {
            categoryList.forEach(index -> stringBuilder.append(index).append(" / "));
            return stringBuilder.substring(0, stringBuilder.lastIndexOf(" / "));
        }
        return stringBuilder.toString();
    }

}
